package com.zzyl.nursing.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.contract.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 *
 * @author XY
 * @date 2025-01-09
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {
        //判断老人是否已经入住
        //查询老人  通过身份证号查询
        Elder elder = elderMapper.selectOne(
                Wrappers.<Elder>lambdaQuery()
                        .eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo())
                        .eq(Elder::getStatus, 1)
        );
        if (ObjectUtils.isNotEmpty(elder)) {
            throw new BaseException("老人已入住");
        }

        //更新床位的状态  已入住
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        /*Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);*/
        //保存或更新老人数据
        elder = insertOrUpdate(bed, checkInApplyDto.getCheckInElderDto());
        //生成合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();
        //新增签约办理
        insertContract(contractNo, elder, checkInApplyDto);
        //新增入住信息
        CheckIn checkIn = insertCheckIn(elder, checkInApplyDto);
        //新增入住配置信息
        insertCheckInConfig(checkIn.getId(), checkInApplyDto);
    }


    /**
     * 新增入住配置
     */
    private void insertCheckInConfig(Long checkInId, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }


    /**
     * 新增入住信息
     */
    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkIn);
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getCheckInConfigDto()));
        checkIn.setElderName(elder.getName());
        checkIn.setStatus(0);
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(elder.getBedNumber());
        checkInMapper.insert(checkIn);
        return checkIn;

        /*CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);
        return checkIn;*/
    }


    /**
     * 新增合同
     */
    private void insertContract(String contractNo, Elder elder, CheckInApplyDto checkInApplyDto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), contract);
        contract.setContractName(elder.getName());
        contract.setContractNumber(contractNo);
        contract.setElderId(elder.getId());

        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        Integer status = startDate.isAfter(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contractMapper.insert(contract);
       /* Contract contract = new Contract();
        //属性拷贝
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setContractNumber(contractNo);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        //状态、开始时间、结束时间
        //签约时间小于等于当前时间，合同生效中
        LocalDateTime checkInStartTime = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = checkInApplyDto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isAfter(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        contractMapper.insert(contract);*/
    }

    /**
     * 新增或更新老人
     */
    private Elder insertOrUpdate(Bed bed, CheckInElderDto checkInElderDto) {
        //准备老人数据
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedId(bed.getId());
        elder.setStatus(1);
        elder.setBedNumber(elder.getBedNumber());
        Elder elder1 = elderMapper.selectOne(
                Wrappers.<Elder>lambdaQuery()
                        .eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())
        );
        if (ObjectUtils.isNotEmpty(elder1)) {
            elderMapper.updateById(elder);
        } else {
            elderMapper.insert(elder);
        }
        return elder;
       /* Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);
        //查询老人信息，(身份证号和状态  0)
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())
                .eq(Elder::getStatus, 0);
        Elder elderDb = elderMapper.selectOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(elderDb)) {
            elderMapper.updateById(elder);
        } else {
            elderMapper.insert(elder);
        }
        return elder;*/
    }

    @Override
    public CheckInDetailVo detail(Long id) {
        //入住信息
        CheckIn checkIn = checkInMapper.selectById(id);
        //老人信息
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        checkInElderVo.setAge(Period.between(LocalDate.parse(checkInElderVo.getBirthday()), LocalDate.now()).getYears());
        //签约办理
        Contract contract = contractMapper.selectOne(
                Wrappers.<Contract>lambdaQuery()
                        .eq(Contract::getElderId, checkIn.getElderId())
        );
        //入住配置
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(
                Wrappers.<CheckInConfig>lambdaQuery()
                        .eq(CheckInConfig::getCheckInId, checkIn.getId())
        );
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setRemark(JSON.toJSONString(checkInConfig));
        checkInConfigVo.setStartDate(contract.getStartDate());
        checkInConfigVo.setEndDate(contract.getEndDate());
        checkInConfigVo.setBedNumber(elder.getBedNumber());
        //家属信息
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        //封装信息并返回
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        return checkInDetailVo;
      /*  //老人信息
        Elder elder = elderMapper.selectElderById(id);
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        checkInElderVo.setAge(Period.between(LocalDate.parse(checkInElderVo.getBirthday()), LocalDate.now()).getYears());

        //签约办理
        Contract contract = contractMapper.selectContract(checkInElderVo.getId());

        //入住配置
        CheckInConfig checkInConfig = checkInConfigMapper.selectCheckInConxfig(id);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setRemark(JSON.toJSONString(checkInConfig));
        checkInConfigVo.setStartDate(contract.getStartDate());
        checkInConfigVo.setEndDate(contract.getEndDate());
        checkInConfigVo.setBedNumber(elder.getBedNumber());

        //家属信息
        CheckIn checkIn = checkInMapper.selectCheckIn(id);
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(remark, ElderFamilyVo.class);

        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        return checkInDetailVo;*/
    }


}
